package com.mediacloud.app.newsmodule.fragment.ugc

import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.assembly.views.BlurTransformation
import com.mediacloud.app.model.activity.SwipeBackFragmentActivity
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.ugc.mod.CmsCatalog
import com.mediacloud.app.newsmodule.utils.GridSpacingItemDecoration
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_liteav_hot_detail.*
import kotlinx.android.synthetic.main.activity_liteav_hot_detail.mRecyclerView
import kotlinx.android.synthetic.main.activity_liteav_hot_detail.mRefreshLayout
import kotlinx.android.synthetic.main.activity_politics_filter.*
import kotlinx.android.synthetic.main.fragment_liteav_home_list.*
import org.json.JSONObject

class LiteAvHotDetailActivity : SwipeBackFragmentActivity(), OnRefreshLoadMoreListener {
    var url =
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F4%2F57d7abcf2070b.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633766387&t=7be409ecb18b272949b6f2fbad83a1a4"
    var catalog: CmsCatalog? = null
    var pageNum = 1
    var pageSize = 20
    var loadingLayout: View? = null
    private lateinit var contentAdapter: LiteAvListAdapter2
    override fun getFitSystemWindow(): Boolean {
        return false
    }

    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_liteav_hot_detail
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        catalog = intent.extras?.getParcelable("CMS_CATALOG");
        back.setOnClickListener { finish() }
        val lp2 = back.layoutParams as ConstraintLayout.LayoutParams
        lp2.topMargin = StatusBarUtil.getStatusBarHeight(this)
        back.layoutParams = lp2

        back.post {
            val lp3 = logo.layoutParams as ConstraintLayout.LayoutParams
            lp3.topMargin = back.bottom + resources.getDimensionPixelSize(R.dimen.dimen6)
            logo.layoutParams = lp3
        }


        mRefreshLayout.setOnRefreshLoadMoreListener(this)
        mRecyclerView.layoutManager = GridLayoutManager(this, 2)
        mRecyclerView.addItemDecoration(GridSpacingItemDecoration(2, resources.getDimensionPixelSize(R.dimen.dimen10), true))
        contentAdapter = LiteAvListAdapter2(this)
        contentAdapter.catalogId = catalog?.id
        mRecyclerView.adapter = contentAdapter
        loadingLayout = findViewById(R.id.mLoadingView)
        getDetail()
        getData()
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        pageNum = 1
//        mRefreshLayout.setEnableLoadMore(false)
//        mRefreshLayout.setEnableRefresh(false)
        getData()

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        pageNum++
//        mRefreshLayout.setEnableLoadMore(false)
//        mRefreshLayout.setEnableRefresh(false)
        getData()
    }

    private fun rendColor(bitmap: Bitmap) {
        Palette.from(bitmap).maximumColorCount(10).generate { palette: Palette? ->
            if (palette == null)
                return@generate
            val s = palette.dominantSwatch//独特的一种
            val s1 = palette.vibrantSwatch       //获取到充满活力的这种色调
            val s2 = palette.darkVibrantSwatch    //获取充满活力的黑
            val s3 = palette.lightVibrantSwatch   //获取充满活力的亮
            val s4 = palette.mutedSwatch           //获取柔和的色调
            val s5 = palette.darkMutedSwatch      //获取柔和的黑
            val s6 = palette.lightMutedSwatch    //获取柔和的亮
            val currentColor = s1 ?: s4 ?: s6
            currentColor?.rgb?.let {
                mRefreshLayout.setHeaderBackgroundColor(it)
            }
        }
    }


    private fun getDetail() {
        DataInvokeUtil.getZiMeiTiApi()
            .getCmsCatalogById(catalog?.id)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: JSONObject) {
                    if (t.optBoolean("state")) {
                        t.optJSONObject("data")?.let {
                            titleText.text = it.optString("name")
                            summary.text = it.optString("metaDescription")
                            var imagePath = it.optString("imagePath")
                            logo.load(imagePath, true)
                          // imagePath = url
                            if (imagePath.isNotEmpty()) {
                                val drawable = AppFactoryGlobalConfig.getDefaultImageLoadDrawable()
                                val option = RequestOptions()
                                    .transform(BlurTransformation(this@LiteAvHotDetailActivity))
                                    .placeholder(drawable)
                                Glide.with(this@LiteAvHotDetailActivity).asBitmap().load(imagePath).apply(option).into(bgImage)
                             //   Glide.with(this@LiteAvHotDetailActivity).asBitmap().load(imagePath).apply(option).into(bgImage1)
                            } else {
                                titleLayout.setBackgroundColor(Color.parseColor("#333333"))
                            }
                        }
                    }
                    loadingLayout?.visibility = View.GONE

                }

                override fun onError(e: Throwable) {
                    loadingLayout?.visibility = View.GONE
                }

                override fun onComplete() {
                    loadingLayout?.visibility = View.GONE
                }
            })
    }

    private fun getData() {
        DataInvokeUtil.getZiMeiTiApi()
            .getMyVideoList(catalog?.id, null, null, pageNum, pageSize)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: JSONObject) {
                    val data = ArticleListData()
                    data.readFromJson(t);
                    success(data)
                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {
                }
            })
    }

    fun success(data: ArticleListData?) {
        mRefreshLayout.setEnableRefresh(true)
        mRefreshLayout.setEnableLoadMore(true)
        mRefreshLayout.finishRefresh()
        mRefreshLayout.finishLoadMore(true)
        data?.let {
            if (pageNum == 1) {
                contentAdapter.data.clear()
            }
            contentAdapter.pageIndex = pageNum
            contentAdapter.addData(it.articleList)
            mRefreshLayout.setNoMoreData(!it.haveMore())
        }
    }
}